package com.chiemy.cardview;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import android.app.Activity;
import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.AccelerateInterpolator;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;







import com.hs.ble.BluetoothLeService;
import com.hs.ble.LeDeviceListAdapter;
import com.hs.ble.SampleGattAttributes;
import com.hs.color.lamp.BluetoothChatService;
import com.hs.color.lamp.ColorLampControlActivity;
import com.hs.color.lamp.ColorPickerDialog;
import com.hs.color.lamp.SppCommandPacket;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorListenerAdapter;
import com.nineoldandroids.view.ViewHelper;
import com.nineoldandroids.view.ViewPropertyAnimator;

public class ColorLampFragment extends Fragment{

	private TextView tv;
	private ListView lv;
	private View root;
	private View view;
	private LeDeviceListAdapter mDeviceListAdapter;
	private String tag = "ColorLampFragment";
	//private LeDeviceListAdapter mLeDeviceListAdapter;
	private Context context;
	private Handler mHandler;
	private boolean mScanning;
	private boolean mSupportBLE = false;
	private boolean mTestBothBleClassic = false;
	private List<BluetoothDevice> mconnectedDevices = null;
	
	public BluetoothLeService mBLE;
	private String mDeviceAddress;
	
	private boolean mBleConnected;
	private boolean mClassicConnected;
	private List<BluetoothGattService> BluetoothGattServices;
	 // Stops scanning after 10 seconds.
    private static final long SCAN_PERIOD = 10000;
    private static final int REQUEST_ENABLE_BT = 1;
    
    private BluetoothAdapter mBleAdapter = null;
    private BluetoothAdapter mClassicAdapter = null;
	
    private BluetoothGattCharacteristic mColorLampCharacteristic = null;
    private int mSendFlag = 0;
    /*classic*/
    // Message types sent from the BluetoothChatService Handler
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST_CONN_LOST = 5;
    public static final int MESSAGE_EXE_COLOR_SELECT = 0x1000;
    // Key names received from the BluetoothChatService Handler
    public static String DEVICE_NAME = "device_name";
    public static String TOAST = "toast";
    
    public static BluetoothChatService mChatService = null;
    public BluetoothA2dp mA2DP;
	public BluetoothHeadset mHfp;
	public BluetoothDevice mDevice;
	private int m_isA2dpConnected = -1;
	//
	private ColorPickerDialog dialog = null;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		this.context = activity;
	}

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		root = inflater.inflate(R.layout.color_lamp_layout, container, false);
		
		initUI(root);
		
		mDeviceListAdapter = new LeDeviceListAdapter((Activity) context);
		
		lv.setAdapter(mDeviceListAdapter);
		mHandler = new Handler();
		
		
		//ble init
		if (!context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
		    Toast.makeText(context, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
		    mSupportBLE = false;
		}else
			mSupportBLE = false;    // TODO configuration 
		
		if(mSupportBLE)
		{
			final BluetoothManager bluetoothManager =
			          (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
			mBleAdapter = bluetoothManager.getAdapter();
			  
			// Checks if Bluetooth is supported on the device.
			if (mBleAdapter == null) {
			    Toast.makeText(context, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
			    ((Activity) context).finish();
			    return root;
			}
			//
			mBleAdapter.enable();
			
			
			//start broadcast-service
			Intent i = new Intent(context, BluetoothLeService.class);
			context.startService(i);
		    boolean res = context.bindService(i, mServiceConnection, context.BIND_AUTO_CREATE);
		    //mBleService = i;
			context.registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
			SampleGattAttributes.initalerpaly();
		}
		
		//classic
		mClassicAdapter = BluetoothAdapter.getDefaultAdapter();
		if(mClassicAdapter == null) 
		{
			Toast.makeText(context, "Bluetooth is not available.", Toast.LENGTH_LONG).show();
			return root;
		}


		if(!mClassicAdapter.isEnabled()) 
		{
			Toast.makeText(context, "请打开您的蓝牙设备，然后重新打开软件！！.", Toast.LENGTH_LONG).show();
			return root;

		}
		context.registerReceiver(searchDevices, classicUpdateIntentFilter());
		//mClassicAdapter.startDiscovery();
		mChatService = new BluetoothChatService(context, mSPPHandler);
		context.registerReceiver(DevicesState, makeDevicesStateIntentFilter());
		
		m_isA2dpConnected = mClassicAdapter.getProfileConnectionState(BluetoothProfile.A2DP);
		if(m_isA2dpConnected == BluetoothProfile.A2DP)
		{
			// TODO get a2dp profixy and get the connected device 
			//spp建立连接之后，获得A2DP的代理
 		   	mClassicAdapter.getProfileProxy(context, A2DPListener, BluetoothProfile.A2DP);
     	    //spp建立连接之后，获得HeadSet的代理
 		    mClassicAdapter.getProfileProxy(context, HFPListener, BluetoothProfile.HEADSET);
		}
		return root;
	}
	
	//{hb+
	
	private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
            	mBleConnected = true;
            	mDeviceListAdapter.clear();
            	mDeviceListAdapter.notifyDataSetChanged();
            	Toast.makeText(context, "BLE connect remote device success!!", Toast.LENGTH_LONG).show();
            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
                
            	mBleConnected = false;
            	Toast.makeText(context, "BLE disconnect remote device success!!", Toast.LENGTH_LONG).show();
            } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                // Show all the supported services and characteristics on the user interface.
            	BluetoothGattServices = mBLE.getSupportedGattServices();
            	// Loops through available GATT Services.
    	        for (BluetoothGattService gattService : BluetoothGattServices) {
    	            
    	            List<BluetoothGattCharacteristic> gattCharacteristics =
    	                    gattService.getCharacteristics();
    	            // Loops through available Characteristics.
    	            for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
    	                //charas.add(gattCharacteristic);
    	                if(SampleGattAttributes.color_lamp_control_uuid.equals(gattCharacteristic.getUuid().toString()))
    	                {
    	                	
    	                	mColorLampCharacteristic = gattCharacteristic;
    	                }
    	            }
    	        }
            	//ShowGattServices(mBLE.getSupportedGattServices());
            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
            	
            }else if(BluetoothLeService.ACTION_GATT_CHARACTER_NOTIFY.equals(action)){		
            	
            }
        }
    };
    
    
    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
        	mBLE = ((BluetoothLeService.LocalBinder) service).getService();
        	Log.i(tag, "in onServiceConnected!!!");
        	if (!mBLE.initialize()) {
                Log.e(tag, "Unable to initialize Bluetooth");
                ((Activity) context).finish();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
        	mBLE = null;
        }
    };
    
    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CHARACTER_NOTIFY);

        return intentFilter;
    }
	
	
	
	private BroadcastReceiver searchDevices = new BroadcastReceiver() { 

	       public void onReceive(Context context, Intent intent) {

	           String action = intent.getAction();

	           Bundle b = intent.getExtras();

	           Object[] lstName = b.keySet().toArray(); 

	           // 显示所有收到的消息及其细节

	           for (int i = 0; i < lstName.length; i++) {

	              String keyName = lstName[i].toString();

	              Log.e(keyName, String.valueOf(b.get(keyName)));

	           }

	           //搜索设备时，取得设备的MAC地址

	           if (BluetoothDevice.ACTION_FOUND.equals(action)) {

	        	   	BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
	            //添加表
					mDeviceListAdapter.addDevice(device);
					mDeviceListAdapter.notifyDataSetChanged();
		        

	           }

	           
	       }

	    };
	    
	    
	//ble scan result
    private BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
        	
//	        	byte[] manuf_data = {2, 1, 5, 26, -1, 76, 0, 2, 21, -3, -91, 6, -109, -92, -30, 79, -79, -81, -49, -58, -21, 7, 100, 120, 37, 39, 17, 48, 57, -56, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
//	        	boolean  res = Arrays.equals(manuf_data, scanRecord);
//	        	if(!res)
//	        		return ;
            
        	((Activity) context).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mDeviceListAdapter.addDevice(device);
                    mDeviceListAdapter.notifyDataSetChanged();
                }
            });
        }
    };
    
	//classic scan result
    private static IntentFilter classicUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        
        return intentFilter;
    }
	
	private void scanDevice(final boolean enable) {
        if (enable) {
            // Stops scanning after a pre-defined scan period.
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mScanning = false;
                    mClassicAdapter.cancelDiscovery();
                }
            }, SCAN_PERIOD);

            mScanning = true;
            boolean res = mClassicAdapter.startDiscovery();
            if(!res)
            {
            	Log.i(tag, "discovery error!");
            }
        } else {
            mScanning = false;
            mClassicAdapter.cancelDiscovery();
        }
    }
	 
	
	private void scanLeDevice(final boolean enable) {
        if (enable) {
        	mBleAdapter.stopLeScan(mLeScanCallback);
        	mDeviceListAdapter.clear();
        	mDeviceListAdapter.notifyDataSetChanged();
            // Stops scanning after a pre-defined scan period.
        	mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mScanning = false;
                    mBleAdapter.stopLeScan(mLeScanCallback);
                    //invalidateOptionsMenu();
                }
            }, SCAN_PERIOD);

            mScanning = true;
            mBleAdapter.startLeScan(mLeScanCallback);
        } else {
            mScanning = false;
            mBleAdapter.stopLeScan(mLeScanCallback);
        }
        //invalidateOptionsMenu();
    }
	
	//classic 
	//a2dp call back
	private  BluetoothProfile.ServiceListener A2DPListener = new  BluetoothProfile.ServiceListener(){
	
		@Override
		public void onServiceConnected(int profile, BluetoothProfile proxy) {
			// TODO Auto-generated method stub
			BluetoothA2dp a2dp = (BluetoothA2dp) proxy;
			mA2DP = a2dp;
			Toast.makeText(context, "A2DP service connected!", Toast.LENGTH_SHORT).show();
			//TODO
			if(m_isA2dpConnected == BluetoothProfile.A2DP)
			{
				mconnectedDevices = mA2DP.getConnectedDevices();
				 
			}
			
			if(mA2DP.isA2dpPlaying(mDevice))
			{
				Toast.makeText(context, "The other application is use a2dp!", Toast.LENGTH_SHORT).show();
				return;
			}
        	Class<? extends BluetoothA2dp> clazz = mA2DP.getClass();
        	Method m2 = null;
        	try {
				m2 = clazz.getMethod("connect",BluetoothDevice.class);
				
			} catch (NoSuchMethodException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        	try {
				m2.invoke(mA2DP, mDevice);
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        	
		}
	
		@Override
		public void onServiceDisconnected(int profile) {
			// TODO Auto-generated method stub
			
		}
		
		
	};
	
	//HFP call back
	private  BluetoothProfile.ServiceListener HFPListener = new  BluetoothProfile.ServiceListener(){
	
		@Override
		public void onServiceConnected(int profile, BluetoothProfile proxy) {
			// TODO Auto-generated method stub
			mHfp = (BluetoothHeadset) proxy;
			
			//HandSet connect 
        	if(mHfp.isAudioConnected(mDevice))
			{
				
				return;
			}
        	Class<? extends BluetoothHeadset> clazz1 = mHfp.getClass();
        	Method m3 = null;
        	try {
				m3 = clazz1.getMethod("connect",BluetoothDevice.class);
				
			} catch (NoSuchMethodException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        	try {
				m3.invoke(mHfp, mDevice);
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	
		@Override
		public void onServiceDisconnected(int profile) {
			// TODO Auto-generated method stub
			
		}
		
		
	};
	
	private BroadcastReceiver DevicesState = new BroadcastReceiver() { 

	       public void onReceive(Context context, Intent intent) {

	           String action = intent.getAction();
	           
	           if(BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action))
	           {
	        	   Toast.makeText(context, "acl disconnect !!!", Toast.LENGTH_SHORT).show();
	        	   mClassicConnected = false;
	        	   return ;
	           }
	           if(BluetoothDevice.ACTION_ACL_CONNECTED.equals(action))
	           {
	        	   Toast.makeText(context, "acl connect !!!", Toast.LENGTH_SHORT).show();
//	        	   Toast.makeText(context, "spp connect success!!!", Toast.LENGTH_SHORT).show();
//	        	   if(m_isA2dpConnected == -1)
//	        	   {
//	        		   //spp建立连接之后，获得A2DP的代理
//	        		   mClassicAdapter.getProfileProxy(context, A2DPListener, BluetoothProfile.A2DP);
//                	   //spp建立连接之后，获得HeadSet的代理
//	        		   mClassicAdapter.getProfileProxy(context, HFPListener, BluetoothProfile.HEADSET);
//	        	   }
//                	mClassicConnected = true;
                	
//                	Message msg = mSPPHandler.obtainMessage(MESSAGE_EXE_COLOR_SELECT);
//                	mSPPHandler.sendMessage(msg);
	           }
	           
	           if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))
	           {
	        	   ((Activity) context).setProgressBarIndeterminateVisibility(false);
	           }
	           
	           if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action))
	           {
	        	   ((Activity) context).setProgressBarIndeterminateVisibility(true);
	           }
	           
	       }   

	    };
	
	 private static IntentFilter makeDevicesStateIntentFilter() {
	     final IntentFilter intentFilter = new IntentFilter();
	     intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
	     intentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
	     intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
	     intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
	     
	     //intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
	     return intentFilter;
	 }
	 
	 
	//classic spp connect 
	private void ConnectDevice()
	{
		if (mChatService != null) {
	        // Only if the state is STATE_NONE, do we know that we haven't started already
	        if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
	        	// Start the Bluetooth chat services
	        	mChatService.start();
	        }
	        if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) 
	        {
	        	BluetoothDevice device = mClassicAdapter.getRemoteDevice(mDeviceAddress);
	        	mChatService.connect(device, false);
	        	mDevice = device;
			}
	    }else
	    {
	    	Toast.makeText(context, "mChatService is null", Toast.LENGTH_SHORT).show();
	    }
	
	//        BluetoothDevice device = mClassicAdapter.getRemoteDevice(mDeviceAddress);
	//        //mDevice = device;
	//        // Attempt to connect to the device
	//        mChatService.connect(device, true);
	 
	}
	
	private final Handler mSPPHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MESSAGE_STATE_CHANGE:
                Log.i(tag, "MESSAGE_STATE_CHANGE: " + msg.arg1);
                switch (msg.arg1) {
                case BluetoothChatService.STATE_CONNECTED:
                	Toast.makeText(context, R.string.title_connected, Toast.LENGTH_SHORT).show();
 	        	    Toast.makeText(context, "spp connect success!!!", Toast.LENGTH_SHORT).show();
 	        	    if(m_isA2dpConnected != BluetoothProfile.A2DP )
 	        	    {
 	        		    //spp建立连接之后，获得A2DP的代理
 	        		    mClassicAdapter.getProfileProxy(context, A2DPListener, BluetoothProfile.A2DP);
                 	    //spp建立连接之后，获得HeadSet的代理
 	        		    mClassicAdapter.getProfileProxy(context, HFPListener, BluetoothProfile.HEADSET);
 	        	    }
                	mClassicConnected = true;
                	//setStatus(R.string.title_connected);
                	Message msg1 = mSPPHandler.obtainMessage(MESSAGE_EXE_COLOR_SELECT);
                	mSPPHandler.sendMessage(msg1);
                    break;
                case BluetoothChatService.STATE_CONNECTING:
                	Toast.makeText(context, R.string.title_connecting, Toast.LENGTH_SHORT).show();
                    
                    break;
                case BluetoothChatService.STATE_LISTEN:
                	
                	break;
                case BluetoothChatService.STATE_NONE:
                	Toast.makeText(context, R.string.title_not_connected, Toast.LENGTH_SHORT).show();
                	mClassicConnected = false;
                    break;
                }
                break;
            case MESSAGE_WRITE:
                byte[] writeBuf = (byte[]) msg.obj;
                // construct a string from the buffer
                String writeMessage = new String(writeBuf);
                
                break;
            case MESSAGE_READ:
                byte[] readBuf = (byte[]) msg.obj;
                // construct a string from the valid bytes in the buffer
                String readMessage = new String(readBuf, 0, msg.arg1);
                
                break;
            case MESSAGE_DEVICE_NAME:
                // save the connected device's name
                
                break;
            case MESSAGE_TOAST_CONN_LOST:
                Toast.makeText(context, msg.getData().getString(TOAST),
                               Toast.LENGTH_SHORT).show();
                mClassicConnected = false;
                mChatService.stop();
                break;
                
            case MESSAGE_EXE_COLOR_SELECT:
            	Intent enableBtIntent = new Intent(context, ColorLampControlActivity.class);
                //enableBtIntent.putExtra("DEVICE_ADDRESS", "");
                //enableBtIntent.putExtra("BLUETOOTH_CHAT_SERVICE", mChatService);
//                Bundle value = new Bundle();
//                enableBtIntent.putExtra("", value);
                ((Activity) context).startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
				//dialog.show();
            	break;
            }
        }
    };
	
	private void initUI(final View root) {
		root.setClickable(true);
		root.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {}
		});
		tv = (TextView) root.findViewById(R.id.textView);
		lv = (ListView) root.findViewById(R.id.list_device);
		dialog = new ColorPickerDialog(context,  
				"ColorBluetoothLamp", 
				new ColorPickerDialog.OnColorChangedListener() {
			
			@Override
			public void colorChanged(int color) {
				//TODO send color
				byte[] mCmdPacket = null;
				byte[] color_array = new byte[4];
				Utils.int4_to_bytearray(color, color_array);
				//mCmdPacket = SppCommandPacket.getSendSppCtrlPacket(color_array);
				mCmdPacket = SppCommandPacket.getSendPWMCtrlPacket(color_array);
				
//				if(mTestBothBleClassic)
//            	{
//            		if(mSendFlag % 2 == 0)
//            		{
//            			//ble
//            			if(mSupportBLE && mBleConnected)
//            			{
//            				if(mColorLampCharacteristic == null)
//            				{
//            					Toast.makeText(context, "no PWMCTL character", Toast.LENGTH_SHORT).show();
//            					return ;
//            				}
//            				mColorLampCharacteristic.setValue(mCmdPacket);
//            				mBLE.writeCharacteristic(mColorLampCharacteristic);
//            				Toast.makeText(context, "ble send command", Toast.LENGTH_SHORT).show();
//            			}else
//            			{
//            				Toast.makeText(context, "ble is not connected!!", Toast.LENGTH_SHORT).show();
//            				if(mClassicConnected)
//            				{
//            					
//            					if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
//            					    Toast.makeText(context, "spp not connected", Toast.LENGTH_SHORT).show();
//            					    return;
//            					}
//            					mChatService.write(mCmdPacket);
//            					Toast.makeText(context, "spp send command", Toast.LENGTH_SHORT).show();
//            				}
//            			}
//            		}else
//            		{
//            		
//        				if(mClassicConnected)
//        				{
//        					if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
//        					    Toast.makeText(context, "spp not connected", Toast.LENGTH_SHORT).show();
//        					    return;
//        					}
//        					mChatService.write(mCmdPacket);
//        					Toast.makeText(context, "spp send command", Toast.LENGTH_SHORT).show();
//        				}
//            			
//            		}
//            	}
				// just ble
//				else if(mSupportBLE && mBleConnected)
//    			{
//    				mColorLampCharacteristic.setValue(mCmdPacket);
//    				mBLE.writeCharacteristic(mColorLampCharacteristic);
//    				Toast.makeText(context, "ble send command", Toast.LENGTH_SHORT).show();
//    			}
//				//just spp
//				else
    			{
    				if(mClassicConnected)
    				{
    					if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
    					    Toast.makeText(context, "spp not connected", Toast.LENGTH_SHORT).show();
    					    return;
    					}
    					mChatService.write(mCmdPacket);
    					Toast.makeText(context, "spp send command", Toast.LENGTH_SHORT).show();
    				}
    			}
			}
		});
		root.findViewById(R.id.button).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				root.setClickable(false);
				ViewPropertyAnimator.animate(root)
				.rotationY(-90).setDuration(200)
				.setListener(new AnimatorListenerAdapter(){
					@Override
					public void onAnimationEnd(Animator animation) {
						root.clearAnimation();
						root.setVisibility(View.GONE);
						view.setEnabled(true);
					}
				});
				
				if(mSupportBLE)
            	{
            		if(mBleConnected){
            			mBLE.disconnect();
            		}
            		if(mScanning)
            			scanLeDevice(false);
            		
            	}else
            	{
            		if(mScanning)
            			scanDevice(false);
            	}
				if(mClassicConnected)
				{
					//TODO disconnect classic device 
					if(mChatService != null)
						mChatService.stop();
				}
				
				mDeviceListAdapter.clear();
	        	mDeviceListAdapter.notifyDataSetChanged();
				
			}
		});
		
		root.findViewById(R.id.scanBtn).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mDeviceListAdapter.clear();
            	mDeviceListAdapter.notifyDataSetChanged();
            	if(mChatService.getState() == mChatService.STATE_CONNECTED)
            	{
            		mChatService.stop();
            	}
            	if(mSupportBLE)
            	{
            		if(mBleConnected){
            			mBLE.disconnect();
            		}
            		scanLeDevice(false);
            		scanLeDevice(true);
            	}else
            	{
            		if(mconnectedDevices != null)
	            		for(BluetoothDevice device : mconnectedDevices){
	    					mDeviceListAdapter.addDevice(device);
	    					mDeviceListAdapter.notifyDataSetChanged();
	    				}
            		
            		scanDevice(false);
            		scanDevice(true);
            	}
            	
            	
			}
		});
		
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				final BluetoothDevice device = mDeviceListAdapter.getDevice(position);
		        if (device == null) return;
		        if (mScanning) {
		        	if(mSupportBLE)
		        		scanLeDevice(false);
		        	else
		        		scanDevice(false);
		            mScanning = false;
		        }
		        mDeviceAddress = device.getAddress();
		        
		        if(mSupportBLE)
		        {
		        	if(mBLE == null)
			        	return ;
		        	boolean res = mBLE.connect(mDeviceAddress);
		        	if(!res)
		        		Log.i(tag, "call ble connect failed");
		        }
		        
		        // TODO add cassic device connect 
		       
		        ConnectDevice();
		        
		        mDeviceListAdapter.clear();
		        mDeviceListAdapter.notifyDataSetChanged();
		        
			}
			
		});
		
		
		ViewHelper.setRotationY(view, 0);
		ViewHelper.setRotationY(root, -90);
		root.setVisibility(View.VISIBLE);
		
		ViewPropertyAnimator.animate(view).rotationY(90)
		.setDuration(300).setListener(null)
		.setInterpolator(new AccelerateInterpolator());
		
		
		ViewPropertyAnimator.animate(root)
		.rotationY(0).setDuration(200).setStartDelay(300)
		.setListener(new AnimatorListenerAdapter() {
			@Override
			public void onAnimationEnd(Animator animation) {
				ViewHelper.setRotationY(view, 0);
			}
		});
	}
	
	public void show(final View view,Bundle bundle){
		view.setEnabled(false);
		this.view = view;
		
		if(root == null)
			return ;
		
		ViewHelper.setRotationY(view, 0);
		ViewHelper.setRotationY(root, -90);
		root.setVisibility(View.VISIBLE);
		
		ViewPropertyAnimator.animate(view).rotationY(90)
		.setDuration(300).setListener(null)
		.setInterpolator(new AccelerateInterpolator());
		
		
		ViewPropertyAnimator.animate(root)
		.rotationY(0).setDuration(200).setStartDelay(300)
		.setListener(new AnimatorListenerAdapter() {
			@Override
			public void onAnimationEnd(Animator animation) {
				ViewHelper.setRotationY(view, 0);
			}
		});
	}
}
